package com.stox.ui.javafx.core.widget.wrapper;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;

import com.stox.design.Callback;

public class TreeView<T> extends javafx.scene.control.TreeView<T> {

	public TreeView() {
		super();
	}

	public TreeView(TreeItem<T> paramTreeItem) {
		super(paramTreeItem);
	}

	public class SearchEventHandler implements EventHandler<ActionEvent>{
		
		private final START start;
		private final DIRECTION direction;
		private final TextField textField;
		private final Callback<TreeItem<T>, Void> callback;
		
		public SearchEventHandler(Callback<TreeItem<T>, Void> callback, TextField textField, START start, DIRECTION direction) {
			this.start = start;
			this.direction = direction;
			this.textField = textField;
			this.callback = callback;
		}
		
		@Override
		public void handle(ActionEvent arg0) {
			callback.execute((TreeItem<T>)search(textField.getText(), start, direction));
		}
	}
	
	
	public static enum START{
		FIRST, SELECTED, LAST;
	}
	
	public static enum DIRECTION{
		BACKWARD, FORWARD;
	}
	
	public TreeItem<T> search(Object text, START start, DIRECTION direction) {
		TreeItem<T> root = (TreeItem<T>)getRoot();
		TreeItem<T> startItem = start.equals(START.FIRST) ? (TreeItem<T>)getRoot() :
			start.equals(START.LAST) ? root.getLastLeaf() : (TreeItem<T>)getSelectionModel().getSelectedItem();
		TreeItem<T> treeItem = direction.equals(DIRECTION.FORWARD) ? startItem.nextTreeItem() : startItem.previousTreeItem();
		do {
			if(treeItem == null) break;
			if(text instanceof String) {
				String treeItemValue = treeItem.getValue().toString();
				if(treeItemValue.trim().toUpperCase().contains(text.toString().trim().toUpperCase())) {
					return treeItem;
				}
			}
			
			treeItem = direction.equals(DIRECTION.FORWARD) ? treeItem.nextTreeItem() : treeItem.previousTreeItem();
		}while(treeItem != null);
		return null;
	}

}
